import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getUser } from '@/lib/authUtils'

// 强制动态渲染，因为需要访问请求头
export const dynamic = 'force-dynamic'

// 获取用户信息
export async function GET(request: NextRequest) {
  try {
    const userid = await getUser(request)
    if (!userid) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 })
    }
    if (userid instanceof NextResponse) {
      return userid
    }

    const user = await prisma.vms_user.findUnique({
      where: { id: userid },
      select: {
        id: true,
        email: true,
        name: true,
        zcsj: true,
        ai_count: true,
        ai_count_limit: true,
        copy_count: true,
        copy_count_limit: true,
        script_count: true,
        script_count_limit: true,
        topic_count: true,
        topic_count_limit: true,
        voice_count: true,
        voice_count_limit: true,
        subtitle_count: true,
        subtitle_count_limit: true,
        vip_type: true,
        vip_end_time: true,
        status: true,
        roles: true
      }
    })

    if (!user) {
      return NextResponse.json({ error: '用户不存在' }, { status: 404 })
    }

    // 将 zcsj 重命名为 createdAt 以保持前端兼容性
    const userResponse = {
      ...user,
      createdAt: user.zcsj
    }

    return NextResponse.json(userResponse)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return NextResponse.json({ error: '服务器错误' }, { status: 500 })
  }
}

// 更新用户信息（仅允许修改用户名）
export async function PUT(request: NextRequest) {
  try {
    const userid = await getUser(request)
    if (!userid) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 })
    }
    if (userid instanceof NextResponse) {
      return userid
    }

    const body = await request.json()
    const { name } = body

    // 验证输入 - 用户名可以为空
    if (name && typeof name !== 'string') {
      return NextResponse.json({ error: '用户名格式不正确' }, { status: 400 })
    }

    // 更新用户信息（仅更新用户名）
    const updatedUser = await prisma.vms_user.update({
      where: { id: userid },
      data: {
        name: name || null
      },
      select: {
        id: true,
        email: true,
        name: true,
        zcsj: true,
        ai_count: true,
        ai_count_limit: true,
        copy_count: true,
        copy_count_limit: true,
        script_count: true,
        script_count_limit: true,
        topic_count: true,
        topic_count_limit: true,
        voice_count: true,
        voice_count_limit: true,
        subtitle_count: true,
        subtitle_count_limit: true,
        vip_type: true,
        vip_end_time: true,
        status: true,
        roles: true
      }
    })

    // 将 zcsj 重命名为 createdAt 以保持前端兼容性
    const userResponse = {
      ...updatedUser,
      createdAt: updatedUser.zcsj
    }

    return NextResponse.json(userResponse)
  } catch (error) {
    console.error('更新用户信息失败:', error)
    return NextResponse.json({ error: '服务器错误' }, { status: 500 })
  }
}